//
//  File.cpp
//  VideoParse
//
//  Created by xiaerfei on 2020/2/10.
//  Copyright © 2020 erfeixia. All rights reserved.
//

#include "File.hpp"
#include <fstream>
#include <iostream>

using namespace std;

class FileContext {
    
public:
    ifstream *fd;
    int trunc;
    int blocksize;
    int follow;
};

File::File(char *url, int flag) {
    url_open(url, flag);
}

int File::url_open(char *url, int flag) {
    ifstream *fd = new ifstream();
    if (NULL == fd) { return -1; }
    try {
        fd->open(url,ios::in);
    } catch (const char* msg) {
        cout<<"打开文件失败："<< msg << endl;
        return -1;
    }
    FileContext *fc = new FileContext();
    fc->fd = fd;
    this->private_data = fc;
    return 0;
}

long File::url_read(char *buf, int size) {
    ifstream *fd = ((FileContext *)this->private_data)->fd;
    fd->read(buf, size);
    return fd->gcount();
}

int File::url_write(const unsigned char *buf, int size) {
    return 0;
}

int64_t File::url_seek(int64_t pos, int whence) {
    ifstream *fd = ((FileContext *)this->private_data)->fd;
    fd->seekg(pos);
    return fd->gcount();
}

int File::url_close() {
    ifstream *fd = ((FileContext *)this->private_data)->fd;
    fd->close();
    return 0;
}

int File::url_get_file_handle() {
    return 0;
}

File::~File() {
    url_close();
    ifstream *fd = ((FileContext *)this->private_data)->fd;
    delete fd;
}
